<template>
    <div class="pageSize">
        <el-container class="container">
            <el-header class="el-height">
                <el-row class="header-top">
                    <el-col :span="6">
                        <div class="header-inline-left">
                            <img src="@/assets/img/favicon.png" alt="logo" class="header-inline-img"
                                @click="toHomePage()">
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="header-inline-center">全球最快的在线购物平台。</div>
                    </el-col>
                    <el-col :span="6">
                        <div class="header-inline-right">
                            <el-icon size="24" class="header-dropdown-icon" title="购物车" @click="toShowPage('cart')">
                                <ShoppingCart />
                            </el-icon>
                            <el-divider direction="vertical" class="header-dropdown-divider" />
                            <el-dropdown class="header-dropdown-dropdown">
                                <div class="el-dropdown-link">
                                    菜单导航
                                    <el-icon size="24" class="frop-icon">
                                        <arrow-down />
                                    </el-icon>
                                </div>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item>
                                            <div class="header-dropdown-item" @click="toShowPage('products')">商品列表</div>
                                        </el-dropdown-item>
                                        <el-dropdown-item>
                                            <div class="header-dropdown-item" @click="toShowPage('orders')">订单管理</div>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                            <el-divider direction="vertical" class="header-dropdown-divider" />
                            <el-dropdown trigger="click">
                                <el-icon size="24" class="header-dropdown-icon" v-if="!userLogin">
                                    <User />
                                </el-icon>
                                <div class="header-dropdown-avatar" v-if="userLogin">
                                    <el-avatar> user </el-avatar>
                                </div>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item v-if="!userLogin">
                                            <div class="header-dropdown-item" @click="loginClick">登录</div>
                                        </el-dropdown-item>
                                        <el-dropdown-item v-if="!userLogin">
                                            <div class="header-dropdown-item" @click="registerClick">注册</div>
                                        </el-dropdown-item>
                                        <el-dropdown-item v-if="userLogin">
                                            <div class="header-dropdown-item" @click="logoutClick"
                                                v-loading.fullscreen.lock="fullscreenLoading"
                                                element-loading-text="正在登出中。。。">登出</div>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>

                        </div>
                    </el-col>
                </el-row>
            </el-header>
            <el-main class="el-height main">
                <Breadcrumb />

                <router-view :key="uniqueKey"></router-view>
            </el-main>
            <el-footer class="el-height">
                <el-row class="footer-row">
                    <el-col :span="6">
                        <div class="grid-content ep-bg-purple">
                            <div class="footer">
                                <img src="@/assets/img/logo.png" alt="logo" class="footer-row-img">
                                <p class="footer-row-type">
                                    让每个人都能够享受科技购物的快乐！
                                </p>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="grid-content ep-bg-purple">
                            <div class="footer">
                                <p class="footer-row-type">
                                    技术支持
                                </p>
                                <el-divider />
                                <a href="" class="footer-row-link" target="_blank">
                                    API Explorer
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    SDK中心
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    Huawei Cloud Developer Experts
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    Huawei Cloud Developer Group
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    Huawei Cloud Student Developers
                                </a>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="grid-content ep-bg-purple">
                            <div class="footer">
                                <p class="footer-row-type">
                                    关于
                                </p>
                                <el-divider />
                                <a href="" class="footer-row-link" target="_blank">
                                    网站信息
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    产品 / 服务信息
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    合作伙伴和联盟
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    法律声明和免责条款
                                </a>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="grid-content ep-bg-purple">
                            <div class="footer">
                                <p class="footer-row-type">
                                    联系方式
                                </p>
                                <el-divider />
                                <a href="" class="footer-row-link link-ad" target="_blank">
                                    XX 国 xxx 省 xxx 市 xxx 区 xxxx 街道 xxxx 路 001 号
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    +86 111 1111 1111
                                </a>
                                <a href="" class="footer-row-link" target="_blank">
                                    example@email.com
                                </a>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </el-footer>
        </el-container>
    </div>
    <el-backtop class="backtop" :visibility-height="40" :right="100" :bottom="100" />


    <!-- 登录弹框 -->
    <el-dialog v-model="centerDialogVisible" title="登录" width="500" center :close-on-click-modal=false
        :destroy-on-close=true :show-close=false>
        <!-- <Login /> -->
        <div class="login-logo">
            <img src="@/assets/img/favicon.png" alt="logo">
        </div>
        <el-form label-position="right" label-width="auto" size="large" :model="longinParam" :disabled="buLoading"
            class="login-form">
            <el-form-item label="账号：" label-position="">
                <el-input v-model="longinParam.account" />
            </el-form-item>
            <el-form-item label="密码：" label-position="">
                <el-input v-model="longinParam.password" type="password" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" color="#777777" plain class="dialog-bu" :disabled="buLoading"
                    @click="centerDialogVisible = false">取消</el-button>
                <el-button size="large" color="#5CAF90" plain class="dialog-bu" :loading="buLoading"
                    @click="startLogin">
                    登录
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { HttpMethod } from '@/api/types';
import { apiRequest } from '@/api/apiService';
import { ref, onMounted, reactive } from 'vue';
import { AuthService } from '@/api/authService';
import { useRouter, useRoute } from 'vue-router';
import Breadcrumb from '@/components/commerce/Breadcrumb.vue';

const route = useRoute();               // 路由对象
const uniqueKey = ref(0);               // 初始化为0或任何唯一值
const router = useRouter();             // 获取路由实例
const responseData = ref();             // 响应数据
const buLoading = ref(false);           // 按钮loading
const userLogin = ref(false);           // 登陆状态
const fullscreenLoading = ref(false);   // 全页面loading
const centerDialogVisible = ref(false); // 登陆弹框展示
const longinParam = reactive({          // 登陆参数
    account: '',
    password: ''
})

// 使用 onMounted 生命周期钩子在应用挂载后运行初始化函数
onMounted(() => {
    AuthService.removeToken();
    longinParam.account = '';
    longinParam.password = '';
});

// 路由跳转
const toShowPage = (pageName: string) => {
    router.push({ name: pageName });
}

// 首页
const toHomePage = () => {
    router.push({ name: '/' });
}

// 登录点击
const loginClick = () => {
    const matched = route.matched.slice(0); // 排除根路由
    if (matched[0].name == 'register') {
        // 仅在注册界面时，强行跳到首页
        toHomePage();
    }
    centerDialogVisible.value = true;
    longinParam.account = '';
    longinParam.password = '';
}

// 开始登录
const startLogin = () => {
    buLoading.value = true;
    userLogin.value = false;
    if (longinParam.account.length === 0 || longinParam.password.length === 0) {
        ElMessage({
            message: '表单项存在空值，请补全！',
            type: 'error',
        });
        buLoading.value = false;
    } else {
        toLogin();
    }
}

// 登出点击
const logoutClick = () => {
    fullscreenLoading.value = true
    toLogout();
}

// 注册点击
const registerClick = () => {
    router.push({ name: 'register' });
}

// 是否刷新路由
// 检查条件并刷新路由的函数
const checkConditionAndRefresh = () => {
    const matched = route.matched.slice(0); // 排除根路由
    if (matched[0].name == 'cart' || matched[0].name == 'orders') {
        uniqueKey.value += 1;
    }
};

// 发送登录请求
const toLogin = async () => {
    try {
        const url = '/auth/login';
        const response = await apiRequest.request<any>(HttpMethod.POST, url, longinParam);
        responseData.value = response;
        ElMessage({
            message: '登陆成功',
            type: 'success',
        });
        if (AuthService.isTokenSet()) {
            AuthService.removeToken();
        }
        if(responseData?.value){
            AuthService.setToken(responseData.value.token);
        }
        buLoading.value = false;
        centerDialogVisible.value = false;
        userLogin.value = true;
        checkConditionAndRefresh();
    } catch (error) {
        console.log('request: /api/auth/login failed, error message: ', error);
        buLoading.value = false;
        centerDialogVisible.value = false;
    }
};

// 发送登出请求
const toLogout = async () => {
    try {
        const url = '/auth/logout';
        const customHeaders = { 'Authorization': AuthService.getToken() };
        await apiRequest.request<any>(HttpMethod.POST, url, longinParam, customHeaders);
        ElMessage({
            message: '登出成功',
            type: 'success',
        });
        AuthService.removeToken();
        fullscreenLoading.value = false;
        userLogin.value = false;
        checkConditionAndRefresh();
    } catch (error) {
        console.log('request: /api/auth/logout failed, error message: ', error);
        fullscreenLoading.value = false;
    }
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
}

.pageSize {
    width: calc(100vw - 16px);
    height: 100%;
    min-width: 1280px;
    min-height: 720px;
}

.el-height {
    padding: 0 0;
    height: 100%;
}

.header-top {
    height: 48px;
    line-height: 48px;
    color: #777777;
    font-family: "Poppins, sans-serif";
    font-size: 16px;
    font-weight: 400;
    background-color: #F8F8FB;
    padding: 0 1vw;
}

.header-inline-img {
    margin: 8px 0;
}

.header-inline-left {
    width: 100%;
    display: inline-block;
    text-align: left;
}

.header-inline-center {
    width: 100%;
    display: inline-block;
    text-align: center;
}

.header-inline-right {
    width: 100%;
    display: inline-block;
    text-align: right;
    line-height: 0px;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.el-dropdown-link:focus {
    outline: none;
}

.header-dropdown-icon:focus {
    outline: none;
}

.header-dropdown-avatar {
    margin: 4px 12px;
}

.header-dropdown-icon {
    margin: 12px 20px;
}

.header-dropdown-divider {
    height: 30px;
    top: -8px;
}

.header-dropdown-dropdown {
    margin: 0 20px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 400;
}

.header-dropdown-dropdown:hover {
    border: none;
}

.header-dropdown-item {
    font-size: 16px;
    font-weight: 400;
    margin: 10px 0;
}

.footer {
    width: 80%;
}

.footer-row {
    height: 240px;
    padding: 20px 6vw;
    background-color: #F8F8FB;
}

.footer-row-type {
    color: #4B5966;
    display: block;
    font-family: "Poppins, sans-serif";
    font-size: 18px;
    font-weight: 500;
    line-height: 21.6px;
    margin-bottom: 20px;
    padding-bottom: 15px;
}

.footer-row-img {
    display: block;
    line-height: 24px;
    margin: 40px 0;
    max-width: 144px;
}

.footer-row-link {
    color: #777777;
    cursor: pointer;
    display: block;
    font-family: "Poppins, sans-serif";
    font-size: 14px;
    font-weight: 400;
    height: 20px;
    letter-spacing: normal;
    line-height: 20px;
    margin: 6px 0;
    background-color: transparent;
}

.footer-row-link:hover {
    color: #5CAF90;
    background-color: transparent;
}

.frop-icon {
    top: 6px;
}

.main {
    flex: 1;
    min-height: calc(100vh - 288px);
}

.link-ad {
    display: inline-block;
}

.backtop {
    color: #5CAF90;
}

.dialog-bu {
    width: 100px;
    margin: 0 10px;
}

.login-logo {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}

.login-form {
    margin: 20px;
}
</style>